package com.lcicl.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lcicl.reggie.common.BaseContext;
import com.lcicl.reggie.common.R;
import com.lcicl.reggie.entity.ShoppingCart;
import com.lcicl.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/*
  Date: 2023/10/23
  Author: Luochao
  Description:
*/
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    ShoppingCartService shoppingCartService;

    @GetMapping("/list")
    public R<List> list() {
        Long currentId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, currentId);
        List<ShoppingCart> list = shoppingCartService.list(queryWrapper);

        return R.success(list);
    }

    @DeleteMapping("/clean")
    public R<String> clean() {
        Long currentId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, currentId);

        shoppingCartService.remove(queryWrapper);
        return R.success("删除成功");
    }


    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart) {
        Long currentId = BaseContext.getCurrentId();
        shoppingCart.setUserId(currentId);
        shoppingCart.setNumber(1);//默认一份

        ShoppingCart add = shoppingCartService.add(shoppingCart);
        return R.success(add);
    }

    @PostMapping("/sub")
    public R<ShoppingCart> sub(@RequestBody ShoppingCart shoppingCart) {
        System.out.println(shoppingCart);

        Long currentId = BaseContext.getCurrentId();
        shoppingCart.setUserId(currentId);

        //查询是否还有该项购物车记录
        ShoppingCart shoppingCarted = shoppingCartService.selectOne(shoppingCart);
        if ( shoppingCarted == null) {//已经清空
            return R.error("该商品已清空");
        }
        //减少操作
        ShoppingCart decrease = shoppingCartService.decrease(shoppingCarted);

        return R.success(decrease);
    }



}
